#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <unistd.h>

using namespace std;

int main() {
    //  1.创建socket
    int clientFd = socket(AF_INET, SOCK_STREAM, 0);

    if(clientFd < 0) {
        cout << "create client failed" << endl;
        return -1;
    }
    // 2.发起tcp连接
    const char* ip = "127.0.0.1";
    const uint16_t port = 13400;

    struct sockaddr_in severAddr;
    memset(&severAddr, 0, sizeof(struct sockaddr_in));
    severAddr.sin_family = AF_INET;
    severAddr.sin_port = htons(port);
    severAddr.sin_addr.s_addr = inet_addr(ip);

    if(connect(clientFd, (sockaddr*)(&severAddr), sizeof(severAddr)) < 0) {
        cout << "connect failed" << endl;
        return -1;
    }
    cout << "connect success" << endl;

    string buf;
    while(true) {
        getline(cin, buf);
        if(buf == "q") {
            close(clientFd);
            break;
        } else {
            size_t size = buf.size();
            if(size != write(clientFd, buf.c_str(), size)) {
                cout << "write error" << endl;
            }

            char readBuf[1024] = {0};
            int nread = read(clientFd, readBuf, 1024);
            if(nread <= 0) {
                close(clientFd);
                break;
            } else {
                cout << readBuf << endl;
            }
        }
    }
    return 0;
}